const _SIZE = 1024 * 1024 * 1; //分片大小5M
const THREAD_NUM = navigator.hardwareConcurrency || 4; //开启多线程的数量
export async function cutFile(file,fileSize=5){
	return new Promise(resolve =>{
		const chunkCount = Math.ceil(file.size / (_SIZE * fileSize));//分片的数量
		const threaChunkCount = Math.ceil(chunkCount / THREAD_NUM);
		const result = []
		let finishCount = 0;//标记完成的线程数量
		for(let i = 0; i < THREAD_NUM; i++){
			//分配线程任务
			const worker = new Worker(new URL('./worker.js', import.meta.url), {
				type: 'module',
			 });
			const start = i * threaChunkCount;//线程开始的下标
			let end = (i + 1) * threaChunkCount;//线程结束的下标
			if(end > chunkCount){
				end = chunkCount
			}
			worker.postMessage({
				file,
				start,
				end,
				_SIZE
			})
			//完成后结果
			worker.onmessage = (e) => {
				result[i] = e.data;
				worker.terminate();//关闭线程
				finishCount++;
				if(finishCount == THREAD_NUM){
					resolve(result.flat())//结果扁平化
				}
			};
		}
	})
}